package io.gitee.hefren.hhdeferredresult.demo.controller;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;

/**
 * @Date 2024/6/9
 * @Author lifei
 */
@RestController
@RequestMapping(value = "/demoController")
public class DemoController {

    private final MultiValueMap<String, DeferredResult<Long>> map = new LinkedMultiValueMap<>();

    @RequestMapping(value = "/version/{name}", method = RequestMethod.GET)
    public DeferredResult<Long> version(@PathVariable("name") String name) {
        DeferredResult<Long> deferredResult = new DeferredResult<>();
        deferredResult.onCompletion(()->{
            System.out.println("==> deferredResult onCompletion: " + name);
            map.remove(name);
        });
        deferredResult.onTimeout(()->{
            System.out.println("==> deferredResult onTimeout: " + name);
            map.remove(name);
        });
        deferredResult.onError((e)->{
            System.out.println("==> deferredResult onError: " + e.getMessage());
            map.remove(name);
        });
        map.add(name, deferredResult);
        return deferredResult;
    }

    @RequestMapping(value = "/push/{name}/{version}", method = RequestMethod.GET)
    public void push(@PathVariable("name") String name, @PathVariable("version") Long version) {
        List<DeferredResult<Long>> deferredResults = map.get(name);
        for (DeferredResult<Long> deferredResult : deferredResults) {
            deferredResult.setResult(version);
        }
    }
}
